#include "widget.h"
#include "ui_widget.h"
#include <QMessageBox>
#include <QTcpSocket>
Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    this->setWindowTitle("服务器");

    tcpServer = new QTcpServer(this);

    connect(tcpServer,&QTcpServer::newConnection,this,&Widget::processConnection);
    bool ret = tcpServer->listen(QHostAddress::Any,8081);
    if(!ret)
    {
        QMessageBox::critical(this,"服务器启动失败",tcpServer->errorString());
        exit(1);
    }

}

Widget::~Widget()
{
    delete ui;
}

void Widget::processConnection()
{
    QTcpSocket* clientSocket = tcpServer->nextPendingConnection();
    QString log = "[" + clientSocket->peerAddress().toString()+":"+QString::number(clientSocket->peerPort())+"] 客户端链接成功";
    ui->listWidget->addItem(log);

    connect(clientSocket,&QTcpSocket::readyRead,this,[=](){
        QString request = clientSocket->readAll();

        const QString& response = process(request);

        clientSocket->write(response.toUtf8());
        QString log = "["+clientSocket->peerAddress().toString()+":"+QString::number(clientSocket->peerPort())+"]"
                +" req:"+request+" resp:"+response;
        ui->listWidget->addItem(log);
    });

    connect(clientSocket,&QTcpSocket::disconnected,this,[=]()
    {
        QString log = "[" + clientSocket->peerAddress().toString()+":"+QString::number(clientSocket->peerPort())+"] 客户端断开成功";
        ui->listWidget->addItem(log);

        clientSocket->deleteLater();
    });
}

QString Widget::process(const QString &request)
{
    return request;
}

